/* ----------------------------------------------------------------------
*
* Copyright (C) 2024 XiaoFei. All rights reserved.
*
* @file:		KangWei_AD9834.c
* @author:		XiaoFei
* @Date:     	01-December-2024
* @Revision: 	V1
* @Project: 	XiaoFei BSP Library
*
* -------------------------------------------------------------------- */

#include "stm32f4xx.h"
#include "KangWei_AD9834.h"

/* 
* @function: 	KangWei_AD9834_Write_16Bits
* @parameter:	[in] data					 The number you want to write.
*/
static void KangWei_AD9834_Write_16Bits(unsigned int data) 
{ 
	AD9834_SCK(1); 
	AD9834_FSY(0); 
	for(unsigned int i=0;i<16;i++)      
	{
		AD9834_SDA(!(!(data&0x8000))); 
		AD9834_SCK(0);
		data<<=1; 
		AD9834_SCK(1); 
	} 
	AD9834_SDA(1); 
	AD9834_FSY(1);
} 

/* 
* @function: 	KangWei_AD9834_Init
*/
void KangWei_AD9834_Init(void)
{
	AD9834_RCC_FSY(1);
	AD9834_RCC_SCK(1);
	AD9834_RCC_SDA(1);
	AD9834_RCC_RST(1);
	AD9834_RCC_FS(1);
	AD9834_RCC_PS(1);
	GPIO_InitTypeDef GPIO_InitStructure; 
	GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz; 
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT ;		
	GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;	
	GPIO_InitStructure.GPIO_Pin=AD9834_Pin_FSY; 
	GPIO_Init(AD9834_Port_FSY,&GPIO_InitStructure);
	GPIO_InitStructure.GPIO_Pin=AD9834_Pin_SCK; 
	GPIO_Init(AD9834_Port_SCK,&GPIO_InitStructure);
	GPIO_InitStructure.GPIO_Pin=AD9834_Pin_SDA; 
	GPIO_Init(AD9834_Port_SDA,&GPIO_InitStructure);
	GPIO_InitStructure.GPIO_Pin=AD9834_Pin_RST; 
	GPIO_Init(AD9834_Port_RST,&GPIO_InitStructure);
	GPIO_InitStructure.GPIO_Pin=AD9834_Pin_FS; 
	GPIO_Init(AD9834_Port_FS,&GPIO_InitStructure);
	GPIO_InitStructure.GPIO_Pin=AD9834_Pin_PS; 
	GPIO_Init(AD9834_Port_PS,&GPIO_InitStructure);
	AD9834_FS(0);
	AD9834_PS(0);
	KangWei_AD9834_Write_16Bits(0x2100);
	KangWei_AD9834_Write_16Bits(0x2038);
	KangWei_AD9834_Write_16Bits(0XC000);
	KangWei_AD9834_Write_16Bits(0x2100);
}

/* 
* @function: 	KangWei_AD9834_SetFrequency
* @parameter:   [in] reg				A register used to write frequency words.
* @parameter:   [in] fre				The frequency you want to write.
* @parameter:   [in] type			    The type of waveform you want to generate.
*/
void KangWei_AD9834_SetFrequency(AD9834_FreqRegDef reg, float fre, AD9834_TypeDef type)
{
	unsigned long val=(268435456.0/AD9834_SYSTEM_COLCK)*fre;
	unsigned short int freqHi=reg;
	unsigned short int freqLo=reg;
	freqHi|=((val&0xFFFC000)>>14);
	freqLo|=((val&0x3FFF));
	KangWei_AD9834_Write_16Bits(type);
	KangWei_AD9834_Write_16Bits(freqLo);
	KangWei_AD9834_Write_16Bits(freqHi);
}

/* 
* @function: 	KangWei_AD9834_SetPhase
* @parameter:   [in] reg				A register used to write phase words.
* @parameter:   [in] val				The phase you want to write.
*/
void KangWei_AD9834_SetPhase(AD9834_PhaseRegDef reg, unsigned short int val)
{
	KangWei_AD9834_Write_16Bits(reg|val);
}


